package com.example.goods_manage.interceptor;

import com.example.goods_manage.commons.enums.TokenEnum;
import com.example.goods_manage.dto.User;
import com.example.goods_manage.mapper.UserMapper;
import com.example.goods_manage.utils.AjaxResult;
import com.example.goods_manage.utils.HttpStatus;
import com.example.goods_manage.utils.JWTUtil;
import com.example.goods_manage.utils.UserThreadLocalUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description: 拦截请求 判断token是否合法
 * 如果合法，则保存当前用户信息，供上下文使用
 * <P> Date: 2024/12/22:8:29
 */

@SuppressWarnings({"unchecked", ""})
@Configuration

public class LoginInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(LoginInterceptor.class);


    @Autowired
    private UserMapper userMapper;

    /**
     * 1.从请求头里面获取到token
     * 2.判断token是否存在，不存在则返回false
     * 3.存在，则判断合法性，不合法，返回false
     * 4.token 合法，获取到用户id，查询用户信息进行保存，返回true
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("cur request uri :{}",requestURI);
        //放行 OPTIONS 请求
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }

        String token = getToken(request);
        log.info("generateToken token :{}", token);

        if (token == null ||
                token.length() == 0 ||
                "null".equals(token) ||
                !JWTUtil.verify(token).equals((TokenEnum.TOKEN_SUCCESS))) {

            response.setContentType("application/json;charset=utf-8");

            String data = new ObjectMapper()
                    .writeValueAsString
                            (AjaxResult.error(HttpStatus.SEE_OTHER, "token 异常 重新登录"));
            log.info("token异常 需要重定向:{}", token);
            response.getWriter().write(data);
            return false;
        }

        Integer uid = JWTUtil.getUid(token);
        //查询用户信息，存放起来
        User user = userMapper.findById(uid);
        //判断用户是否存在
        //if(user == null){
        UserThreadLocalUtils.setUser(user);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtils.clear();
    }

    /**
     * 令牌自定义标识
     */
    public static final String HEADER = "Authorization";
    /**
     * 令牌前缀
     */
    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 获取请求token,替换掉不需要的 部分
     * 原 header 值：Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJpZCI6MSwiZXhwIjoxNzIyMTE2NjExLCJpYXQiOjE3MjA0OTY2MTF9.tYrWgetMwt0-0HB5eeaHbY5fOGr_BfS3W0JWFZdBRsY
     * 需要的是：eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJpZCI6MSwiZXhwIjoxNzIyMTE2NjExLCJpYXQiOjE3MjA0OTY2MTF9.tYrWgetMwt0-0HB5eeaHbY5fOGr_BfS3W0JWFZdBRsY
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER);
        if (!StringUtils.isEmpty(token) && token.startsWith(TOKEN_PREFIX)) {
            token = token.replace(TOKEN_PREFIX, "");
        }
        return token;
    }
}
